package cn.ymjr.customer.service.impl;

import cn.ymjr.customer.dao.SysCustomerMapper;
import cn.ymjr.customer.entity.SysCustomer;
import cn.ymjr.customer.form.DecryptForm;
import cn.ymjr.customer.service.CustomerService;
import cn.ymjr.sys.config.weixin.WeiXinApiUtil;
import cn.ymjr.sys.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Tiny
 * @create 2022/4/1 15:45
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    private final Logger logger = Logger.getLogger(getClass());
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private SysCustomerMapper customerMapper;

    @Override
    public Result getOpenId(String code,Integer inviteId) throws Exception {
        String httpsurl = WeiXinApiUtil.getOAuthTokenUrl(code.trim());
        String jsonStr = new String(HttpUtil.doGet(httpsurl));
        Map<String,String> result = new HashMap<>();
        logger.info(jsonStr);
        Map open = JsonUtil.jsonToMap(jsonStr);
        if(open.get("error")!=null && StringUtils.isNotEmpty(open.get("error").toString())){
            return new Result(false,"授权失败，请重试");
        }
        String openid = open.get("openid").toString();
        String sessionKey = open.get("session_key").toString();
        result.put("sessionKey",sessionKey);
        result.put("openId",openid);
        if(redisUtil.exists(openid)){
            redisUtil.remove(openid);
        }
        redisUtil.set(openid,sessionKey);
        SysCustomer customer = customerMapper.findByOpenId(openid);
        if(customer==null){
            customer = new SysCustomer();
            customer.setOpenId(openid);
            customer.setInviteId(inviteId);
            customer.setCreateTime(DateUtil.getSNowDateTime());
            customerMapper.insertSelective(customer);
            if(inviteId!=null){
                SysCustomer sysCustomer = customerMapper.selectByPrimaryKey(inviteId);
                sysCustomer.setShareCount(sysCustomer.getShareCount()+1);
                customerMapper.updateByPrimaryKeySelective(sysCustomer);
            }
            result.put("needAuth","1");
        }else{
            if(customer.getInviteId()==null && inviteId!=null && !customer.getId().equals(inviteId)){
                customer.setInviteId(inviteId);
                customerMapper.updateByPrimaryKeySelective(customer);
                SysCustomer sysCustomer = customerMapper.selectByPrimaryKey(inviteId);
                sysCustomer.setShareCount(sysCustomer.getShareCount()+1);
                customerMapper.updateByPrimaryKeySelective(sysCustomer);
            }
            if(StringUtils.isEmpty(customer.getMobile())){
                result.put("needAuth","1");
            }else{
                result.put("needAuth","0");
                result.put("token",MD5Util.encode(customer.getMobile()));
                result.put("userId",String.valueOf(customer.getId()));
            }
        }
        return new Result(result);
    }


    @Override
    public Result login(DecryptForm decryptForm) throws Exception {
        String sessionKey = (String)redisUtil.get(decryptForm.getOpenId());
        String decrypt = AesCbcUtil.decrypt(decryptForm.getEncryptedData(), sessionKey, decryptForm.getIv(), "utf-8");
        Map decryp = JsonUtil.jsonToMap(decrypt);
        logger.info(decryp);
        if(decryp.get("phoneNumber")==null){
            return new Result(false,"获取手机号失败");
        }
        String phone = (String) decryp.get("phoneNumber");
        SysCustomer customer = customerMapper.findByOpenId(decryptForm.getOpenId());
        Map result = new HashMap();
        if(customer==null){
            customer = new SysCustomer();
            customer.setMobile(phone);
            customer.setOpenId(decryptForm.getOpenId());
            customer.setCreateTime(DateUtil.getSNowDateTime());
            customerMapper.insertUseGeneratedKeys(customer);
            result.put("userId",customer.getId());
            result.put("token",MD5Util.encode(customer.getMobile()));
        }else{
            customer.setMobile(phone);
            customerMapper.updateByPrimaryKeySelective(customer);
            result.put("userId",customer.getId());
            result.put("token",MD5Util.encode(customer.getMobile()));
        }
        return new Result(result);
    }
}
